<template>
  <view class="exception-management-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-red" :isBack="true">
      <block slot="content">异常管理</block>
      <block slot="right">
        <text class="cuIcon-add" @click="reportException"></text>
      </block>
    </cu-custom>

    <!-- 统计概览 -->
    <view class="stats-overview margin-top bg-white">
      <view class="stats-grid padding">
        <view class="stat-item" @click="filterByStatus('all')">
          <view class="stat-number text-red">{{ exceptionStats.total }}</view>
          <view class="stat-label">总异常</view>
        </view>
        <view class="stat-item" @click="filterByStatus('pending')">
          <view class="stat-number text-orange">{{ exceptionStats.pending }}</view>
          <view class="stat-label">待处理</view>
        </view>
        <view class="stat-item" @click="filterByStatus('processing')">
          <view class="stat-number text-blue">{{ exceptionStats.processing }}</view>
          <view class="stat-label">处理中</view>
        </view>
        <view class="stat-item" @click="filterByStatus('resolved')">
          <view class="stat-number text-green">{{ exceptionStats.resolved }}</view>
          <view class="stat-label">已解决</view>
        </view>
      </view>
    </view>

    <!-- 搜索和筛选 -->
    <view class="search-filter margin-top bg-white">
      <view class="search-bar padding">
        <view class="search-input-wrapper">
          <input v-model="searchKeyword" 
                 placeholder="搜索异常标题或设备" 
                 class="search-input" 
                 @input="onSearch" />
          <text class="cuIcon-search search-icon"></text>
        </view>
      </view>
      <view class="filter-tabs padding-lr">
        <scroll-view scroll-x class="filter-scroll">
          <view class="filter-tab-list">
            <view v-for="tab in filterTabs" :key="tab.value"
                  class="filter-tab" 
                  :class="{ active: currentFilter === tab.value }"
                  @click="changeFilter(tab.value)">
              {{ tab.label }}
            </view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 异常列表 -->
    <view class="exception-list margin-top">
      <view v-for="exception in filteredExceptions" :key="exception.id" 
            class="exception-item bg-white margin-bottom" 
            @click="viewExceptionDetail(exception)">
        <view class="exception-header padding">
          <view class="flex justify-between align-center">
            <view class="exception-title">{{ exception.title }}</view>
            <view class="exception-level" :class="exception.levelClass">
              {{ exception.levelText }}
            </view>
          </view>
          <view class="exception-meta margin-top-sm">
            <text class="text-sm text-gray">设备：{{ exception.equipment }}</text>
            <text class="text-sm text-gray margin-left">类型：{{ exception.type }}</text>
          </view>
        </view>
        
        <view class="exception-content padding-lr">
          <view class="exception-description margin-bottom-sm">
            <text class="text-sm">{{ exception.description }}</text>
          </view>
          
          <view class="exception-reporter flex align-center margin-bottom-sm">
            <text class="text-sm text-gray">报告人：</text>
            <image :src="exception.reporter.avatar || '/static/images/default-avatar.png'" 
                   class="reporter-avatar margin-left-xs"></image>
            <text class="text-sm margin-left-xs">{{ exception.reporter.name }}</text>
            <text class="text-sm text-gray margin-left">{{ formatTime(exception.reportTime) }}</text>
          </view>
          
          <view v-if="exception.handler" class="exception-handler flex align-center margin-bottom-sm">
            <text class="text-sm text-gray">处理人：</text>
            <image :src="exception.handler.avatar || '/static/images/default-avatar.png'" 
                   class="handler-avatar margin-left-xs"></image>
            <text class="text-sm margin-left-xs">{{ exception.handler.name }}</text>
          </view>
          
          <view class="exception-time flex justify-between text-sm text-gray">
            <text>发生时间：{{ formatTime(exception.occurTime) }}</text>
            <text v-if="exception.resolveTime">解决时间：{{ formatTime(exception.resolveTime) }}</text>
          </view>
        </view>

        <!-- 状态和操作 -->
        <view class="exception-footer padding">
          <view class="flex justify-between align-center">
            <view class="exception-status" :class="exception.statusClass">
              {{ exception.statusText }}
            </view>
            <view class="action-buttons flex gap-sm">
              <button v-if="exception.status === 'pending'" 
                      class="cu-btn sm bg-blue" 
                      @click.stop="handleException(exception)">
                处理
              </button>
              <button v-if="exception.status === 'processing'" 
                      class="cu-btn sm bg-green" 
                      @click.stop="resolveException(exception)">
                解决
              </button>
              <button class="cu-btn sm bg-gray line" 
                      @click.stop="viewDetails(exception)">
                详情
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredExceptions.length === 0" class="empty-state text-center padding">
      <text class="cuIcon-warn text-gray" style="font-size: 120rpx;"></text>
      <view class="text-gray margin-top">暂无异常记录</view>
    </view>

    <!-- 处理异常弹窗 -->
    <view v-if="showHandleModal" class="handle-modal" @click="showHandleModal = false">
      <view class="handle-content" @click.stop>
        <view class="handle-header padding">
          <text class="text-lg text-bold">处理异常</text>
          <text class="cuIcon-close float-right" @click="showHandleModal = false"></text>
        </view>
        <view class="handle-form padding">
          <view class="form-item margin-bottom">
            <text class="form-label">处理方案：</text>
            <textarea v-model="handleForm.solution" 
                      placeholder="请输入处理方案" 
                      class="form-textarea"></textarea>
          </view>
          <view class="form-item margin-bottom">
            <text class="form-label">预计完成时间：</text>
            <picker mode="datetime" 
                    :value="handleForm.estimatedTime" 
                    @change="onTimeChange">
              <view class="form-input">
                {{ handleForm.estimatedTime || '请选择时间' }}
              </view>
            </picker>
          </view>
        </view>
        <view class="handle-actions padding">
          <button class="cu-btn bg-gray margin-right" @click="showHandleModal = false">取消</button>
          <button class="cu-btn bg-blue" @click="confirmHandle">确认处理</button>
        </view>
      </view>
    </view>

    <!-- 解决异常弹窗 -->
    <view v-if="showResolveModal" class="resolve-modal" @click="showResolveModal = false">
      <view class="resolve-content" @click.stop>
        <view class="resolve-header padding">
          <text class="text-lg text-bold">解决异常</text>
          <text class="cuIcon-close float-right" @click="showResolveModal = false"></text>
        </view>
        <view class="resolve-form padding">
          <view class="form-item margin-bottom">
            <text class="form-label">解决方案：</text>
            <textarea v-model="resolveForm.solution" 
                      placeholder="请输入具体解决方案" 
                      class="form-textarea"></textarea>
          </view>
          <view class="form-item margin-bottom">
            <text class="form-label">根本原因：</text>
            <textarea v-model="resolveForm.rootCause" 
                      placeholder="请分析根本原因" 
                      class="form-textarea"></textarea>
          </view>
          <view class="form-item margin-bottom">
            <text class="form-label">预防措施：</text>
            <textarea v-model="resolveForm.prevention" 
                      placeholder="请输入预防措施" 
                      class="form-textarea"></textarea>
          </view>
        </view>
        <view class="resolve-actions padding">
          <button class="cu-btn bg-gray margin-right" @click="showResolveModal = false">取消</button>
          <button class="cu-btn bg-green" @click="confirmResolve">确认解决</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import mesApi from '../../../api/mes'

export default {
  data() {
    return {
      searchKeyword: '',
      currentFilter: 'all',
      filterTabs: [
        { label: '全部', value: 'all' },
        { label: '待处理', value: 'pending' },
        { label: '处理中', value: 'processing' },
        { label: '已解决', value: 'resolved' }
      ],
      exceptionStats: {
        total: 0,
        pending: 0,
        processing: 0,
        resolved: 0
      },
      exceptions: [],
      filteredExceptions: [],
      showHandleModal: false,
      showResolveModal: false,
      selectedException: null,
      handleForm: {
        solution: '',
        estimatedTime: ''
      },
      resolveForm: {
        solution: '',
        rootCause: '',
        prevention: ''
      }
    }
  },

  onLoad() {
    this.loadExceptions()
  },

  onPullDownRefresh() {
    this.loadExceptions().then(() => {
      uni.stopPullDownRefresh()
    })
  },

  methods: {
    async loadExceptions() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const response = await mesApi.exception.getList()
        this.exceptions = response.data.map(exception => ({
          ...exception,
          levelClass: this.calculateLevelClass(exception.level),
          levelText: this.calculateLevelText(exception.level),
          statusClass: this.calculateStatusClass(exception.status),
          statusText: this.calculateStatusText(exception.status)
        }))
        
        this.calculateStats()
        this.filterExceptions()
        
      } catch (error) {
        console.error('加载异常失败:', error)
        this.loadMockData()
      } finally {
        uni.hideLoading()
      }
    },

    loadMockData() {
      this.exceptions = [
        {
          id: 1,
          title: '切割机异常停机',
          equipment: '切割机-001',
          type: '设备故障',
          level: 'high',
          status: 'pending',
          description: '切割机在运行过程中突然停机，显示电机过热警告',
          reporter: {
            id: 1,
            name: '张三',
            avatar: ''
          },
          handler: null,
          reportTime: '2024-03-01 10:30:00',
          occurTime: '2024-03-01 10:25:00',
          resolveTime: null,
          levelClass: 'level-high',
          levelText: '高级',
          statusClass: 'status-pending',
          statusText: '待处理'
        },
        {
          id: 2,
          title: '质量检测异常',
          equipment: '检测设备-002',
          type: '质量问题',
          level: 'medium',
          status: 'processing',
          description: '产品尺寸超出公差范围，需要调整设备参数',
          reporter: {
            id: 2,
            name: '李四',
            avatar: ''
          },
          handler: {
            id: 3,
            name: '王五',
            avatar: ''
          },
          reportTime: '2024-03-01 09:15:00',
          occurTime: '2024-03-01 09:10:00',
          resolveTime: null,
          levelClass: 'level-medium',
          levelText: '中级',
          statusClass: 'status-processing',
          statusText: '处理中'
        }
      ]
      
      this.calculateStats()
      this.filterExceptions()
    },

    calculateStats() {
      this.exceptionStats = {
        total: this.exceptions.length,
        pending: this.exceptions.filter(e => e.status === 'pending').length,
        processing: this.exceptions.filter(e => e.status === 'processing').length,
        resolved: this.exceptions.filter(e => e.status === 'resolved').length
      }
    },

    calculateLevelClass(level) {
      const levelMap = {
        'low': 'level-low',
        'medium': 'level-medium',
        'high': 'level-high'
      }
      return levelMap[level] || 'level-medium'
    },

    calculateLevelText(level) {
      const levelMap = {
        'low': '低级',
        'medium': '中级',
        'high': '高级'
      }
      return levelMap[level] || '中级'
    },

    calculateStatusClass(status) {
      const statusMap = {
        'pending': 'status-pending',
        'processing': 'status-processing',
        'resolved': 'status-resolved'
      }
      return statusMap[status] || 'status-pending'
    },

    calculateStatusText(status) {
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'resolved': '已解决'
      }
      return statusMap[status] || '待处理'
    },

    onSearch() {
      this.filterExceptions()
    },

    changeFilter(filter) {
      this.currentFilter = filter
      this.filterExceptions()
    },

    filterByStatus(status) {
      this.currentFilter = status
      this.filterExceptions()
    },

    filterExceptions() {
      let filtered = this.exceptions

      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(exception => 
          exception.title.toLowerCase().includes(keyword) ||
          exception.equipment.toLowerCase().includes(keyword)
        )
      }

      // 状态过滤
      if (this.currentFilter !== 'all') {
        filtered = filtered.filter(exception => exception.status === this.currentFilter)
      }

      this.filteredExceptions = filtered
    },

    viewExceptionDetail(exception) {
      uni.navigateTo({
        url: `/pages/production/exception/detail?id=${exception.id}`
      })
    },

    reportException() {
      uni.navigateTo({
        url: '/pages/production/exception/report'
      })
    },

    handleException(exception) {
      this.selectedException = exception
      this.handleForm = {
        solution: '',
        estimatedTime: ''
      }
      this.showHandleModal = true
    },

    resolveException(exception) {
      this.selectedException = exception
      this.resolveForm = {
        solution: '',
        rootCause: '',
        prevention: ''
      }
      this.showResolveModal = true
    },

    viewDetails(exception) {
      this.viewExceptionDetail(exception)
    },

    onTimeChange(e) {
      this.handleForm.estimatedTime = e.detail.value
    },

    async confirmHandle() {
      if (!this.handleForm.solution.trim()) {
        uni.showToast({
          title: '请输入处理方案',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '提交中...' })
        
        await mesApi.exception.handle(this.selectedException.id, this.handleForm)
        
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })
        
        this.showHandleModal = false
        this.loadExceptions()
        
      } catch (error) {
        console.error('处理失败:', error)
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    async confirmResolve() {
      if (!this.resolveForm.solution.trim()) {
        uni.showToast({
          title: '请输入解决方案',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '提交中...' })
        
        await mesApi.exception.resolve(this.selectedException.id, this.resolveForm)
        
        uni.showToast({
          title: '解决成功',
          icon: 'success'
        })
        
        this.showResolveModal = false
        this.loadExceptions()
        
      } catch (error) {
        console.error('解决失败:', error)
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    formatTime(timeStr) {
      if (!timeStr) return '--'
      const date = new Date(timeStr)
      return `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style lang="scss" scoped>
.exception-management-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.stats-overview {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24rpx;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.search-filter {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .search-input-wrapper {
    position: relative;
    
    .search-input {
      width: 100%;
      height: 80rpx;
      padding: 0 60rpx 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .search-icon {
      position: absolute;
      right: 24rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #999;
    }
  }
  
  .filter-scroll {
    white-space: nowrap;
    
    .filter-tab-list {
      display: inline-flex;
      
      .filter-tab {
        padding: 16rpx 24rpx;
        margin-right: 16rpx;
        border-radius: 20rpx;
        background-color: #f0f0f0;
        color: #666;
        font-size: 24rpx;
        white-space: nowrap;
        
        &.active {
          background-color: #1890ff;
          color: white;
        }
      }
    }
  }
}

.exception-list {
  margin: 0 24rpx;
  
  .exception-item {
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    
    .exception-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .exception-level {
      padding: 8rpx 16rpx;
      border-radius: 16rpx;
      font-size: 24rpx;
      
      &.level-low {
        background-color: #f6ffed;
        color: #52c41a;
      }
      
      &.level-medium {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.level-high {
        background-color: #fff1f0;
        color: #f5222d;
      }
    }
    
    .exception-status {
      padding: 8rpx 16rpx;
      border-radius: 16rpx;
      font-size: 24rpx;
      
      &.status-pending {
        background-color: #fff7e6;
        color: #fa8c16;
      }
      
      &.status-processing {
        background-color: #e6f7ff;
        color: #1890ff;
      }
      
      &.status-resolved {
        background-color: #f6ffed;
        color: #52c41a;
      }
    }
    
    .reporter-avatar,
    .handler-avatar {
      width: 32rpx;
      height: 32rpx;
      border-radius: 50%;
    }
    
    .action-buttons {
      .cu-btn {
        margin-left: 16rpx;
        
        &:first-child {
          margin-left: 0;
        }
      }
    }
  }
}

.handle-modal,
.resolve-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .handle-content,
  .resolve-content {
    background-color: white;
    border-radius: 12rpx;
    margin: 0 48rpx;
    width: calc(100% - 96rpx);
    max-height: 80vh;
    overflow: hidden;
    
    .handle-header,
    .resolve-header {
      border-bottom: 1rpx solid #f0f0f0;
      position: relative;
      
      .cuIcon-close {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font-size: 32rpx;
        color: #999;
      }
    }
    
    .handle-form,
    .resolve-form {
      max-height: 60vh;
      overflow-y: auto;
      
      .form-item {
        .form-label {
          display: block;
          font-size: 28rpx;
          color: #333;
          margin-bottom: 16rpx;
        }
        
        .form-textarea {
          width: 100%;
          min-height: 120rpx;
          padding: 16rpx;
          border: 1rpx solid #d9d9d9;
          border-radius: 8rpx;
          font-size: 28rpx;
          resize: none;
        }
        
        .form-input {
          padding: 16rpx;
          border: 1rpx solid #d9d9d9;
          border-radius: 8rpx;
          font-size: 28rpx;
          color: #333;
        }
      }
    }
    
    .handle-actions,
    .resolve-actions {
      border-top: 1rpx solid #f0f0f0;
      display: flex;
      gap: 16rpx;
      
      .cu-btn {
        flex: 1;
      }
    }
  }
}

.empty-state {
  margin-top: 120rpx;
}
</style>
